import React, { useState } from 'react';
import { Tree } from 'antd';
import reactLogo from "./assets/react.svg";
import { invoke } from "@tauri-apps/api/tauri";
import "./App.css";

const initTreeData = [
  {
    title: 'C:',
    key: '0',
    isLeaf: false,
  }
];

// It's just a simple demo. You can use tree map to optimize update perf.
const updateTreeData = (list, key, children) =>
  list.map((node) => {
    if (node.key === key) {
      return {
        ...node,
        children,
      };
    }
    if (node.children) {
      return {
        ...node,
        children: updateTreeData(node.children, key, children),
      };
    }
    return node;
  });

function App() {
  const [treeData, setTreeData] = useState(initTreeData);
  const onLoadData = ({ key, children }) =>
    new Promise((resolve) => {
      if (children) {
        resolve();
        return;
      }
      setTimeout(() => {
        setTreeData((origin) =>
          updateTreeData(origin, key, [
            {
              title: 'Child Node',
              key: `${key}-0`,
            },
            {
              title: 'Child Node',
              key: `${key}-1`,
            },
          ]),
        );
        resolve();
      }, 1000);
    });

  async function root_path() {
    let root_path = await invoke("root_path");
    let jsonStr = JSON.stringify(root_path);
    document.getElementById("txtResult").value = jsonStr;
  }

  async function list_path_files() {
    let path = document.getElementById("txtPath").value;
    let args = { "path": path };
    let files = await invoke("list_path_files", args);
    let jsonStr = JSON.stringify(files);
    document.getElementById("txtResult").value = jsonStr;
  }

  return (
    <div className="container">
      {
        <Tree loadData={onLoadData} treeData={treeData} />
      }
      <input type='input' id="txtPath" placeholder='输入一个路径'/>
      <textarea id='txtResult' className='log_view'/>
      <button onClick={root_path}>获取系统盘符</button>
      <button onClick={list_path_files}>获取目录文件列表</button>
    </div>
  );
}

export default App;
